<template lang="">
  <div class="capital-transfer">
    <a-form
      layout="inline"
      :model="formState"
      name="horizontal_login"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
      labelAlign="left"
      class="action-form"
    >
      <a-form-item
        :label="$t('ziJi-5')"
        name="turnOut"
        :rules="[{ required: true, message: '请选择资金转出渠道' }]"
      >
        <a-select 
          v-model:value="formState.turnOut" 
          style="width:160px"
          size="large"
          :allowClear="true"
        >
          <a-select-option
            v-for="(item, index) in gameChannelList"
            :key="'g-z-item' + index"
            :value="item.id"
            :disabled="isOptionDisabled(item.id, 'turnOut')"
          >{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        :label="$t('ziJi-6')"
        name="turnIn"
        :rules="[{ required: true, message: '请选择资金转入渠道' }]"
      >
      <a-select 
        v-model:value="formState.turnIn"
        style="width:160px"
        size="large"
        :allowClear="true"
      >
          <a-select-option
            v-for="(item, index) in gameChannelList"
            :key="'g-r-item' + index"
            :value="item.id"
            :disabled="isOptionDisabled(item.id, 'turnIn')"
          >{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        :label="$t('jinE')"
        name="amount"
        :rules="amountRule"
      >
        <a-input-number
          v-model:value="formState.amount"
          style="width:160px"
          size="large"
        ></a-input-number>
      </a-form-item>

      <a-form-item
        label="x"
        class="submit-btn"
      >
        <a-button 
          type="primary" 
          html-type="submit"
          size="large"
          :loading="loading"
          >{{ $t('queD') }}</a-button
        >
      </a-form-item>
    </a-form>

    <div style="margin-top: 20px">
      <p>{{ $t('wenX') }}</p>
      <ul>
        <li>{{ $t('ping-0') }}</li>
        <li>{{ $t('weiK') }}</li>
      </ul>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { walletTransfer } from "@/api/financial";
import { message } from 'ant-design-vue';
import { useUserStore } from "@/stores/userInfo";
import { useGameChannelStore } from '@/stores/gameChannel';
import { useI18n } from 'vue-i18n'
import { useGameInfoStore } from '@/stores/gameInfo';

const { t } = useI18n()
const { user, updateUserInfo } = useUserStore();
const gameChannelStore = useGameChannelStore();
const gameInfoStore = useGameInfoStore();
const loading = ref(false)
const walletBalance = computed(() => user.wallet_balance || 0);
const formState = reactive<any>({
  game_channel_id: '',
  turnOut: null,
  turnIn: null,
  amount: null,
});

const gameChannelList = computed(() => {
  let result: any[] = [];
  if (Array.isArray(gameInfoStore.gameTypeList)) {
    result = gameInfoStore.gameTypeList.map((item: any) => {
      return {
        ...item,
      }
    });
    result.unshift({
      balance: walletBalance.value,
      id: -1,
      name: t('qian'),
    })
  }
  return result;
});
const amountRule = [
  {
    validator: (_: any, value: number) =>
      new Promise((resolve, reject) => {
        if (value <= 0) {
          // 任意渠道，都不允许输入0及以下的金额
          reject(t('qing-19'));
        } else {
          // 平台余额
          if (formState.turnOut === -1) {
            // 从平台转出
            if (value > walletBalance.value) {
              reject(t('chao-1'));
            } else {
              resolve(value);
            }
          } else if (formState.turnIn === -1) {
            // 转入到平台，判断当前转出的游戏渠道余额是否满足
            const curItem = gameChannelList.value.find((item) => item.id === formState.turnOut);
            if (!curItem) {
              reject(t('weiH'));
            } else {
              if (value > curItem.balance) {
                reject(t('chao-2'));
              } else {
                resolve(value);
              }
            }
          } else if (formState.turnOut > 0 && formState.turnIn > 0) {
            // 游戏转入到游戏，判断转出的金额是否满足
            const curItem = gameChannelList.value.find((item) => item.id === formState.turnOut);
            if (!curItem) {
              reject(t('weiH-0'));
            } else {
              if (value > curItem.balance) {
                reject(t('chao-3'));
              } else {
                resolve(value);
              }
            } 
          } else {
            resolve(value);
          }
        }

        
      }),
  },
]

function isOptionDisabled(optionValue: any, currentSelect: any) {
  return Object.keys(formState)
    .filter(key => key !== currentSelect)
    .some(key => formState[key] === optionValue);
}

// 游戏渠道转入到平台
function handleGameTransferToPlatform(gameChannelId: number,requestId: number = Date.now(),loaded: boolean = true) {

  if (loaded) loading.value = true;
  return walletTransfer({
    amount: formState.amount,
    game_channel_id: [gameChannelId],
    ty: 1,
    request_id:requestId,
  }).finally(() => {
    if (loaded) loading.value = false;
  })
}

// 平台转入到游戏渠道
function handlePlatformToGame(gameChannelId: number,requestId: number = Date.now(),loaded: boolean = true) {

  if (loaded) loading.value = true;
  return walletTransfer({
    amount: formState.amount,
    game_channel_id: [gameChannelId],
    ty: 2,
    request_id:requestId,
  }).finally(() => {
    if (loaded) loading.value = false;
  })
}

// 游戏渠道转入到游戏渠道
async function handleGameTransferToGame(originalChannel: number, newChannel: number,requestId: number = Date.now()) {
  try {

    loading.value = true;
    // 从原来的游戏的余额转到平台
    const res = await handleGameTransferToPlatform(originalChannel,requestId,false);
    if (res.status === 'OK') {
      const nRes = await handlePlatformToGame(newChannel,requestId, false);
      if (nRes.status === 'OK') {
        message.success(t('caoZ-1'));
        refresh();
      }
    }
  } catch(error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

function refresh() {
  updateUserInfo({});
  gameInfoStore.updateGameType();
}

const onFinish = async (values: any) => {
  // -1 是平台的钱包余额。

  // 如果转出是钱包余额，则是平台转到游戏
  if (formState.turnOut === -1 && formState.turnIn > 0) {
    const res = await handlePlatformToGame(formState.turnIn);
    if (res.status === 'OK') {
      message.success(t('caoZ-2'));
      refresh();
    }
  } else if (formState.turnIn === -1 && formState.turnOut > 0) {
    // 如果转入是钱包余额，则是游戏转到平台
    const res = await handleGameTransferToPlatform(formState.turnOut);
    if (res.status === 'OK') {
      message.success(t('caoZ-3'));
      refresh();
    }
  } else if (formState.turnOut > 0 && formState.turnIn > 0) {
    // 如果转入和转出都没有选择钱包余额，则认为是游戏转游戏
    await handleGameTransferToGame(formState.turnOut, formState.turnIn);
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
</script>
<style lang="less">
.capital-transfer {
  .action-form {
    .ant-form-item-label {
      display: block !important;
      ;
    }
  }

  .submit-btn {
    .ant-form-item-label {
      opacity: 0;
    }
  }
}
</style>
